package br.edu.ufc.deti.doodlematricula.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import com.javaunderground.jdbc.DebugLevel;
import com.javaunderground.jdbc.StatementFactory;

import br.edu.ufc.deti.doodlematricula.beans.Disciplina;
import br.edu.ufc.deti.doodlematricula.beans.Usuario;

public class PrsUsuario {
    private static PrsUsuario instancia = null;
    
    private PrsUsuario() {}

    public static PrsUsuario getInstancia() {
        if (instancia == null) {
            instancia = new PrsUsuario();
        }
        return instancia;
    }
    public ArrayList<Disciplina> getDisciplinasUsuario(Connection conn, Usuario usuario) throws Exception {
        String select = "";
        ResultSet rs = null;
        ArrayList<Disciplina> disciplinas = new ArrayList<Disciplina>();
        PreparedStatement pstmt = null;

        try {
        	select = "select d.id as idDisciplina, d.codDisciplina, d.dscDisciplina"+
                	 "  from disciplinas d, disciplinas_usuario du "+
                	 " where du.idUsuario = ?"+
                	 "   and du.idDisciplina = d.id";
        	
        	pstmt = StatementFactory.getStatement(conn,select,DebugLevel.OFF);
        	pstmt.setString(1,usuario.getIdUsuario());
        	rs = pstmt.executeQuery();
        	
        	Disciplina disciplina;
            while (rs.next()) {
            	disciplina = new Disciplina();
            	disciplina.setIdDisciplina(rs.getString("idDisciplina"));
            	disciplina.setCodDisciplina(rs.getString("codDisciplina"));
            	disciplina.setDscDisciplina(rs.getString("dscDisciplina"));
            	disciplinas.add(disciplina);
            }
        }catch(Exception e){
        	throw e;
        }finally{
        	if(rs != null) rs.close();
        	if(pstmt != null) pstmt.close();
        }    
		return disciplinas;
	}

	public Usuario getUsuario(Connection conn, String matricula)  throws Exception  {
        String select = "";
        ResultSet rs = null;
        Usuario usuario = new Usuario();
        PreparedStatement pstmt = null;

        try {
        	select = "select id, nome from usuario u where u.matricula = ?";
        	pstmt = StatementFactory.getStatement(conn,select,DebugLevel.OFF);
        	pstmt.setString(1,matricula);
        	rs = pstmt.executeQuery();
        	
        	while (rs.next()) {
            	usuario.setIdUsuario(rs.getString("id"));
            	usuario.setNome(rs.getString("nome"));
            }
        }catch(Exception e){
        	throw e;
        }finally{
        	if(rs != null) rs.close();
        	if(pstmt != null) pstmt.close();
        }    
		return usuario;
	}

}
